package com.hyt.it.ogt.ykcj.utils;

import java.util.Collections;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

/**
 * redis分布式锁
 *
 * @author liuqi
 * @date 2022-06-01
 */
@Component
public class RedisLock {

    private static final Long UNLOCK_SUCCESS = 1L;

    private static final String UNLOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public boolean tryLock(String lockKey, String clientId, int seconds) {
        return stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, seconds, TimeUnit.SECONDS);
    }
    


	public <T> T tryLock(String lockKey, String clientId, int seconds, Callable<T> callable, String erroMsg) throws Exception {
		boolean lockResult = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, clientId, seconds, TimeUnit.SECONDS);
		if (lockResult) {
			try {
				return callable.call();
			} catch (Exception e) {
				unLock(lockKey, clientId);
				throw e;
			}
		} else {
			throw new RuntimeException(erroMsg);
		}
	}

    public boolean unLock(String lockKey, String clientId) {
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<>(UNLOCK_SCRIPT, Long.class), Collections.singletonList(lockKey), clientId);
        if (UNLOCK_SUCCESS.equals(result)) {
            return true;
        } else {
            return false;
        }
    }

}
